<template>
  <div class="cart-container">
    <header class="header">
      <div class="header-left">
        <el-button 
          type="text" 
          @click="goHome" 
          class="back-btn"
          icon="ArrowLeft"
        >
          返回首页
        </el-button>
      </div>
      <h1>购物车</h1>
      <div class="header-right">
        <el-button 
          type="text" 
          @click="viewOrders" 
          class="orders-btn"
          icon="Document"
        >
          我的订单
        </el-button>
      </div>
    </header>

    <div v-if="loading" class="loading-spinner">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else-if="cartItems.length > 0" class="cart-content">
      <!-- 购物车操作栏 -->
      <div class="cart-actions">
        <div class="actions-left">
          <span class="cart-count">共 {{ cartItems.length }} 件商品</span>
        </div>
        <div class="actions-right">
          <el-button 
            type="danger" 
            @click="confirmClearCart"
            class="clear-cart-btn"
            icon="Delete"
            size="small"
            round
          >
            <span class="clear-btn-text">清空购物车</span>
          </el-button>
        </div>
      </div>

      <div class="cart-item" v-for="item in cartItems" :key="item.productId">
        <div class="item-checkbox">
          <el-checkbox v-model="item.selected" @change="calculateTotal" />
        </div>
        <div class="item-image">
          <img :src="item.imageUrl || '/assets/product-default.jpg'" :alt="item.productName" />
          <div class="image-overlay">
            <el-tag size="small" type="success">现货</el-tag>
          </div>
        </div>
        <div class="item-info">
          <div class="item-name">{{ item.productName }}</div>
          <div class="item-desc">{{ item.description }}</div>
          <div class="item-price-quantity">
            <span class="item-price">¥{{ item.price.toFixed(2) }}</span>
            <div class="quantity-control">
              <el-button 
                size="small" 
                @click="decreaseQuantity(item)" 
                :disabled="item.quantity <= 1"
                class="quantity-btn"
              >
                -
              </el-button>
              <el-input-number 
                v-model="item.quantity" 
                :min="1" 
                :max="99" 
                size="small" 
                controls-position="right"
                @change="updateCartItem(item)"
                class="quantity-input"
              />
              <el-button 
                size="small" 
                @click="increaseQuantity(item)"
                class="quantity-btn"
              >
                +
              </el-button>
            </div>
          </div>
        </div>
        <div class="item-actions">
          <el-popconfirm
            title="确定要移除这件商品吗？"
            confirm-button-text="确定移除"
            cancel-button-text="取消"
            confirm-button-type="danger"
            icon="WarningFilled"
            icon-color="#f56c6c"
            @confirm="removeItem(item.productId)"
            @cancel="handleCancelRemove"
            width="220"
            placement="top"
          >
            <template #reference>
              <div class="delete-btn-wrapper">
                <el-button 
                  type="danger" 
                  size="small" 
                  icon="Delete" 
                  circle 
                  class="delete-btn"
                />
                <div class="delete-tooltip">
                  <span class="tooltip-text">点击移除商品</span>
                  <div class="tooltip-arrow"></div>
                </div>
              </div>
            </template>
          </el-popconfirm>
        </div>
      </div>

      <div class="cart-footer">
        <div class="footer-left">
          <div class="select-all">
            <el-checkbox v-model="allSelected" @change="toggleSelectAll">全选</el-checkbox>
          </div>
          <div class="selected-count">
            已选择 {{ selectedCount }} 件商品
          </div>
        </div>
        <div class="footer-right">
          <div class="total-info">
            <span class="total-label">合计：</span>
            <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <el-button 
            class="checkout-btn" 
            type="primary" 
            :disabled="!hasSelectedItems" 
            @click="checkout"
            size="large"
          >
            立即结算 ({{ selectedCount }})
          </el-button>
        </div>
      </div>
    </div>

    <div v-else class="empty-cart">
      <div class="empty-icon">
        <el-icon size="80" color="#ddd"><ShoppingCart /></el-icon>
      </div>
      <div class="empty-text">
        <h3>购物车还是空的哦</h3>
        <p>快去选购心仪的宠物用品吧~</p>
      </div>
      <div class="empty-actions">
        <el-button type="primary" @click="goShopping" size="large">
          <el-icon><Plus /></el-icon>
          去购物
        </el-button>
        <el-button @click="viewOrders" size="large">
          <el-icon><Document /></el-icon>
          查看订单
        </el-button>
      </div>
    </div>

    <!-- 底部导航 - 移动端显示 -->
    <div class="bottom-nav">
      <div class="nav-item">
        <router-link to="/">
          <i class="nav-icon">
            <el-icon><HomeFilled /></el-icon>
          </i>
          <span>首页</span>
        </router-link>
      </div>
      <div class="nav-item active">
        <i class="nav-icon">
          <el-icon><ShoppingCart /></el-icon>
        </i>
        <span>购物车</span>
      </div>
      <div class="nav-item">
        <router-link to="/user">
          <i class="nav-icon">
            <el-icon><User /></el-icon>
          </i>
          <span>个人中心</span>
        </router-link>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  ShoppingCart, 
  HomeFilled, 
  Delete, 
  ArrowLeft, 
  Document, 
  Plus,
  WarningFilled
} from '@element-plus/icons-vue'

interface CartItem {
  productId: number;
  productName: string;
  description: string;
  price: number;
  quantity: number;
  selected: boolean;
  imageUrl: string;
}

const router = useRouter()
const loading = ref(true)
const cartItems = ref<CartItem[]>([])
const allSelected = ref(true)
const totalPrice = ref(0)

// 选中的商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length
})

// 是否有选中的商品
const hasSelectedItems = computed(() => {
  return selectedCount.value > 0
})

// 计算总价
const calculateTotal = () => {
  totalPrice.value = cartItems.value
    .filter(item => item.selected)
    .reduce((sum, item) => sum + item.price * item.quantity, 0)
  
  // 更新全选状态
  allSelected.value = cartItems.value.length > 0 && 
    cartItems.value.every(item => item.selected)
}

// 全选/取消全选
const toggleSelectAll = () => {
  cartItems.value.forEach(item => {
    item.selected = allSelected.value
  })
  calculateTotal()
}

// 返回首页
const goHome = () => {
  router.push('/')
}

// 查看订单
const viewOrders = () => {
  router.push('/orders')
}

// 增加数量
const increaseQuantity = (item: CartItem) => {
  if (item.quantity < 99) {
    item.quantity++
    updateCartItem(item)
  }
}

// 减少数量
const decreaseQuantity = (item: CartItem) => {
  if (item.quantity > 1) {
    item.quantity--
    updateCartItem(item)
  }
}

// 更新购物车商品数量
const updateCartItem = async (item: CartItem) => {
  try {
    await axios.post('/api/user/cart/items', {
      productId: item.productId,
      quantity: item.quantity
    })
    calculateTotal()
    ElMessage.success('数量已更新')
  } catch (error) {
    console.error('更新购物车失败:', error)
    ElMessage.error('更新购物车失败，请稍后重试')
  }
}

// 确认清空购物车
const confirmClearCart = () => {
  if (cartItems.value.length === 0) {
    ElMessage.info('购物车已经是空的了')
    return
  }
  
  ElMessageBox.confirm(
    `确定要清空购物车中的所有 ${cartItems.value.length} 件商品吗？此操作不可恢复！`,
    '清空购物车',
    {
      confirmButtonText: '确定清空',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'clear-cart-dialog',
      dangerouslyUseHTMLString: true
    }
  ).then(() => {
    clearCart()
  }).catch(() => {
    ElMessage.info('已取消清空操作')
  })
}

// 清空购物车
const clearCart = async () => {
  try {
    await axios.delete('/api/user/cart/clear')
    cartItems.value = []
    calculateTotal()
    ElMessage.success('购物车已清空')
  } catch (error) {
    console.error('清空购物车失败:', error)
    ElMessage.error('清空购物车失败，请稍后重试')
  }
}

// 取消移除商品
const handleCancelRemove = () => {
  ElMessage.info('已取消移除')
}

// 移除商品
const removeItem = async (productId: number) => {
  try {
    await axios.delete(`/api/user/cart/items/${productId}`)
    
    const index = cartItems.value.findIndex(item => item.productId === productId)
    if (index !== -1) {
      const itemName = cartItems.value[index].productName
      cartItems.value.splice(index, 1)
      calculateTotal()
      ElMessage.success(`「${itemName}」已从购物车移除`)
    }
  } catch (error) {
    console.error('移除商品失败:', error)
    ElMessage.error('移除商品失败，请稍后重试')
  }
}

// 前往购物
const goShopping = () => {
  router.push('/')
}

// 结算
const checkout = () => {
  // 获取选中的商品ID
  const selectedItems = cartItems.value
    .filter(item => item.selected)
    .map(item => item.productId)
  
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  
  // 检查选中商品的库存
  const outOfStockItems = cartItems.value
    .filter(item => item.selected && item.quantity > item.stock)
  
  if (outOfStockItems.length > 0) {
    ElMessage.warning('部分商品库存不足，请调整数量后再结算')
    return
  }
  
  // 跳转到结算页面，并传递选中的商品ID
  router.push({
    path: '/checkout',
    query: { items: selectedItems.join(',') }
  })
}

// 获取购物车数据
const fetchCartItems = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/user/cart')
    
    if (response.data && response.data.items) {
      // 转换接口返回的数据格式
      cartItems.value = response.data.items.map((item: any) => ({
        productId: item.productId,
        productName: item.name,
        description: item.description || '',
        price: parseFloat(item.price),
        quantity: item.quantity,
        selected: true, // 默认全选
        imageUrl: item.mainImageUrl || '../assets/homelogo.png'
      }))
      calculateTotal()
    } else {
      cartItems.value = []
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error)
    ElMessage.error('获取购物车数据失败，请稍后重试')
    
    // 使用本地数据作为后备
    cartItems.value = [
      {
        productId: 1,
        productName: '乌龟',
        description: '温顺友好，性格温和',
        price: 300,
        quantity: 1,
        selected: true,
        imageUrl: '../assets/homelogo.png'
      },
      {
        productId: 2,
        productName: '大宠爱内外驱虫滴剂',
        description: '有效驱除体内外寄生虫',
        price: 100,
        quantity: 1,
        selected: true,
        imageUrl: '../assets/homelogo.png'
      }
    ]
    calculateTotal()
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchCartItems()
})
</script>

<style scoped>
.cart-container {
  width: 100%;
  min-height: 100vh;
  margin: 0;
  padding: 0;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  color: white;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left,
.header-right {
  flex: 1;
}

.header-right {
  text-align: right;
}

.back-btn,
.orders-btn {
  color: white !important;
  font-weight: 500;
  transition: all 0.3s ease;
}

.back-btn:hover,
.orders-btn:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
  transform: translateY(-1px);
}

.header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  text-align: center;
  flex: 1;
}

.loading-spinner {
  padding: 30px;
  background-color: white;
  margin: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.cart-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 购物车操作栏样式 */
.cart-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 24px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.cart-count {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.clear-cart-btn {
  font-size: 14px;
  font-weight: 600;
  background-color: #ff4757;
  border-color: #ff4757;
  color: white;
  padding: 8px 20px;
  border-radius: 20px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3);
}

.clear-cart-btn:hover {
  background-color: #ff3742;
  border-color: #ff3742;
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 71, 87, 0.4);
}

.clear-cart-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3);
}

.clear-btn-text {
  text-align: center;
  white-space: nowrap;
}

/* 确保图标和文字垂直居中 */
.clear-cart-btn .el-icon {
  font-size: 16px;
  margin-right: 0;
}

.cart-item {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 16px;
  margin-bottom: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.cart-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.item-checkbox {
  margin-right: 20px;
}

.item-image {
  width: 120px;
  height: 120px;
  border-radius: 12px;
  overflow: hidden;
  margin-right: 24px;
  border: 2px solid #f0f0f0;
  position: relative;
  transition: all 0.3s ease;
}

.item-image:hover {
  transform: scale(1.02);
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 8px;
  color: #2c3e50;
}

.item-desc {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 16px;
  line-height: 1.4;
}

.item-price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  color: #e74c3c;
  font-weight: 700;
  font-size: 20px;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f8f9fa;
  padding: 4px;
  border-radius: 8px;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  font-weight: 600;
}

.quantity-input {
  width: 80px;
}

.item-actions {
  margin-left: 24px;
}

/* 删除按钮增强样式 */
.delete-btn-wrapper {
  position: relative;
  display: inline-block;
}

.delete-btn {
  transition: all 0.3s ease;
  position: relative;
  z-index: 2;
}

.delete-btn:hover {
  transform: scale(1.15);
  box-shadow: 0 6px 20px rgba(231, 76, 60, 0.4);
}

.delete-tooltip {
  position: absolute;
  bottom: 120%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(231, 76, 60, 0.95);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  z-index: 10;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.delete-tooltip::before {
  content: '⚠️';
  margin-right: 4px;
}

.tooltip-arrow {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid rgba(231, 76, 60, 0.95);
}

.delete-btn-wrapper:hover .delete-tooltip {
  opacity: 1;
  visibility: visible;
  transform: translateX(-50%) translateY(-4px);
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  background: white;
  margin: 20px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.empty-icon {
  margin-bottom: 24px;
  opacity: 0.6;
}

.empty-text h3 {
  font-size: 24px;
  color: #2c3e50;
  margin-bottom: 8px;
  font-weight: 600;
}

.empty-text p {
  font-size: 16px;
  color: #7f8c8d;
  margin-bottom: 32px;
}

.empty-actions {
  display: flex;
  gap: 16px;
}

.cart-footer {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  background: white;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
  margin-top: 24px;
  border-radius: 16px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.selected-count {
  font-size: 14px;
  color: #7f8c8d;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-info {
  text-align: right;
}

.total-label {
  font-size: 16px;
  color: #2c3e50;
}

.total-price {
  color: #e74c3c;
  font-weight: 700;
  font-size: 24px;
  margin-left: 8px;
}

.checkout-btn {
  font-size: 16px;
  font-weight: 600;
  padding: 12px 32px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.checkout-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.checkout-btn:disabled {
  background: #bdc3c7;
  transform: none;
  box-shadow: none;
}

/* 底部导航 - 只在移动端显示 */
.bottom-nav {
  display: none;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
  padding: 12px 0;
  z-index: 100;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
  color: #7f8c8d;
  transition: all 0.3s ease;
}

.nav-item.active {
  color: #667eea;
}

.nav-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.nav-item a {
  text-decoration: none;
  color: inherit;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s ease;
}

.nav-item:hover {
  color: #667eea;
  transform: translateY(-2px);
}

/* 自定义确认对话框样式 */
:deep(.clear-cart-dialog) {
  border-radius: 12px;
}

:deep(.clear-cart-dialog .el-message-box__header) {
  background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

:deep(.clear-cart-dialog .el-message-box__content) {
  padding: 20px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .cart-container {
    padding-bottom: 80px;
  }
  
  .header {
    padding: 16px;
    flex-direction: column;
    gap: 12px;
  }
  
  .header h1 {
    font-size: 20px;
  }
  
  .header-left,
  .header-right {
    flex: none;
  }
  
  .cart-actions {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .cart-item {
    flex-direction: column;
    align-items: flex-start;
    padding: 20px;
  }
  
  .item-image {
    width: 100%;
    height: 200px;
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .item-price-quantity {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    width: 100%;
  }
  
  .item-actions {
    margin-left: 0;
    margin-top: 16px;
    align-self: flex-end;
  }
  
  .delete-tooltip {
    bottom: 140%;
    font-size: 11px;
    padding: 6px 10px;
  }
  
  .cart-footer {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }
  
  .footer-left,
  .footer-right {
    width: 100%;
    justify-content: center;
  }
  
  .total-info {
    text-align: center;
  }
  
  .bottom-nav {
    display: flex;
    justify-content: space-around;
  }
  
  .empty-actions {
    flex-direction: column;
    width: 100%;
    max-width: 300px;
  }
}

@media (min-width: 769px) {
  .bottom-nav {
    display: none;
  }
  
  .cart-content {
    padding-bottom: 100px;
  }
}
</style>